package com.cac.demo.util;

import com.alibaba.fastjson.JSON;
import com.cac.demo.newCode.interfaceLog.entity.InterfaceLog;
import com.cac.demo.newCode.interfaceLog.service.InterfaceLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class InterfaceLogAspect {

    @Resource
    private InterfaceLogService interfaceLogService;

    @Around("@annotation(logInterface)")
    public Object logAround(ProceedingJoinPoint joinPoint, LogInterface logInterface) throws Throwable {
        long startTime = System.currentTimeMillis();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
        String ip = request != null ? request.getRemoteAddr() : "unknown";
        String url = request != null ? request.getRequestURL().toString() : "unknown";
        String userAgent = request != null ? request.getHeader("User-Agent") : "unknown";
        
        // 创建日志对象
        InterfaceLog interfaceLog = new InterfaceLog()
                .setDescription(logInterface.description())
                .setUrl(url)
                .setMethod(className + "." + methodName)
                .setIp(ip)
                .setUserAgent(userAgent)
                .setCreateTime(new Date());
        // 记录请求参数
        if (logInterface.logParams()) {
            interfaceLog.setParams(JSON.toJSONString(args));
        }
        Object result = null;
        try {
            result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            // 记录响应结果
            if (logInterface.logResponse()) {
                interfaceLog.setResponse(JSON.toJSONString(result));
            }
            if (logInterface.logExecutionTime()) {
                interfaceLog.setExecutionTime(BigDecimal.valueOf(endTime - startTime));
            }
            interfaceLog.setStatus(0);
            
            // 保存日志
            interfaceLogService.saveLog(interfaceLog);
            
            return result;
        } catch (Exception e) {
            // 记录错误信息
            interfaceLog.setStatus(1);
            interfaceLog.setErrorMsg(e.getMessage());
            interfaceLogService.saveLog(interfaceLog);
            throw e;
        }
    }
} 